<template>
  <view class="container">
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="nav-title">我的预约</view>
    </view>

    <!-- 预约卡片 -->
    <view class="appointment-list">
      <view v-if="appointment.day" class="appointment-card">
        <view class="card-header">
          <view class="consultant-info">
            <u-image :src="consultantAvatar" width="120rpx" height="120rpx" shape="circle"></u-image>
            <view class="info-content">
              <text class="consultant-name">{{ consultantName }}</text>
              <view class="appointment-time">
                <u-icon name="calendar" color="#6c8eef" size="28"></u-icon>
                <text>{{ appointment.day }}</text>
              </view>
            </view>
          </view>
        </view>
        
        <view class="card-content">
          <view class="time-slots">
            <view class="section-title">预约时段</view>
            <view class="slots-list">
              <view class="slot-item">
                <u-icon name="clock" color="#6c8eef" size="24"></u-icon>
                <text>{{ appointment.appointedSlot }}</text>
              </view>
            </view>
          </view>
        </view>

        <view class="card-footer">
          <view class="btn-group">
            <button class="chat-btn"
              @tap.stop="goToChat(consultantToken)" 
              :style="{ backgroundColor: isTimeReached ? '#6c8eef' : '#cccccc', color: 'white' }"
            >
              <u-icon name="chat-fill" color="#ffffff" size="28"></u-icon>
              <text>进入会话</text>
            </button>
            <button class="cancel-btn" @click="handleCancel"
			:disabled="!appointment || isStarted">
              <u-icon name="close-circle" color="#ff5a5f" size="24"></u-icon>
              <text>取消</text>
            </button>
          </view>
		  <button 
		    @click="handleRatingClick" 
			:class="['rating-btn', (!isStarted || haveRated) ? 'disabled-btn' : 'active-btn']">
		    评分
		  </button>
<!-- 		  <button @click="goToChatNoLimit(consultantToken)">直接进入(开发者选项)</button> -->
        </view>
      </view>

      
      <view v-else class="empty-state">
        <u-empty mode="data" text="暂无预约记录"></u-empty>
      </view>
    </view>
	
	<!--评分弹窗-->
	<u-popup :show="showRating" mode="center" bgColor="transparent">
		<view class="popupwin">
			<div class="popTitle">
				为咨询师打个分吧
			</div>
			<div class="close" @click="getHide">
				<u-icon name="close"></u-icon>
			</div>
			<div class="score">
				<div class="title">整体咨询</div>
				<u-rate :gutter="0" count="5" active-color="#fcdc0d" inactive-color="#d8d8d8" v-model="value1">
				</u-rate>
			</div>
			<div class="submit" @click="submitRating()">
				提交
			</div>
		</view>
	</u-popup>
	
	<!--隐私协议弹窗-->
	<u-modal
	  :show="showPrivacyModal"
	  title="隐私协议"
	  show-cancel-button
	  confirm-text="同意并进入"
	  @confirm="confirmPrivacy"
	  @cancel="cancelPrivacy"
	>
	  <view style="font-size: 28rpx; line-height: 1.6;">
	      <text>
	        为提升咨询服务质量，我们可能会在严格匿名的前提下，收集部分咨询过程中的信息用于心理研究。您的个人隐私将受到严格保护，所有数据仅用于科研分析。
	      </text>
	      <view style="margin-top: 20rpx;">
	        <text>
	          请您在继续前阅读并同意
	        </text>
	        <text style="color: #007aff;" @click.stop="goToPrivacyPage">《隐私协议》</text>
	        <text>。</text>
	      </view>
	    </view>
	</u-modal>
  </view>
</template>

<script>
export default {
  data() {
    return {
		value1:3,                 //默认评分
	  showRating:false,				//评分flag
	   haveRated: false,
	  showPrivacyModal: false,		
	  pendingConsultantToken: null,
      appointment: {
        day: '',
        appointedSlot:''
      },
      consultantName: '',
      consultantAvatar: '',
      consultantToken: '',
	  consultantId:','
    };
  },
  computed: {
	isStarted() {
	  // 获取当前真实时间
	  const now = Date.now();
	  // 如果没有预约时段或日期，则全部为灰色
	  if (!this.appointment || !this.appointment.appointedSlot || !this.appointment.day) {
	    return false;
	  }
	  // 解析预约时间段
	  const [startTime, endTime] = this.appointment.appointedSlot.split('-');
	  // 构建预约开始和结束的时间戳（兼容iOS日期格式）
	  const slotStart = new Date((this.appointment.day + ' ' + startTime).replace(/-/g, '/')).getTime();
	  const slotEnd = new Date((this.appointment.day + ' ' + endTime).replace(/-/g, '/')).getTime();
	  // 仅当当前时间在 appointedSlot 范围内时返回 true
	  return now >= slotStart;
	},
  	isTimeReached() {
  	  // 获取当前真实时间
  	  const now = Date.now();
  	  // 如果没有预约时段或日期，则全部为灰色
  	  if (!this.appointment || !this.appointment.appointedSlot || !this.appointment.day) {
  	    return false;
  	  }
  	  // 解析预约时间段
  	  const [startTime, endTime] = this.appointment.appointedSlot.split('-');
  	  // 构建预约开始和结束的时间戳（兼容iOS日期格式）
  	  const slotStart = new Date((this.appointment.day + ' ' + startTime).replace(/-/g, '/')).getTime();
  	  const slotEnd = new Date((this.appointment.day + ' ' + endTime).replace(/-/g, '/')).getTime();
  	  // 仅当当前时间在 appointedSlot 范围内时返回 true
  	  return now >= slotStart && now <= slotEnd;
  	},
	
	canRate() {
	  // 获取当前真实时间
	  const now = Date.now();

	  // 如果没有预约时段或日期，则全部为灰色
	  if (!this.appointment || !this.appointment.appointedSlot || !this.appointment.day) {
		return false;
	  }

	  // 解析预约时间段
	  const [startTime, endTime] = this.appointment.appointedSlot.split('-');

	  // 构建预约开始和结束的时间戳（兼容iOS日期格式）
	  const slotStart = new Date((this.appointment.day + ' ' + startTime).replace(/-/g, '/')).getTime();
	  const slotEnd = new Date((this.appointment.day + ' ' + endTime).replace(/-/g, '/')).getTime();

	  // 如果时间没到，就不能评分
	  if (now < slotEnd) {
		return false;
	  }

	  // 检查本地存储
	  try {
		const haveRated = uni.getStorageSync('have_rated');
		return haveRated !== true;  // 只有当未评分时，才允许评分
	  } catch (e) {
		// 没有设置过，默认可评分
		return true;
	  }
	}


  },
  onLoad() {
    this.getAppointment();
	
	try {
	    const val = uni.getStorageSync('have_rated');
	    this.haveRated = val === true;
	  } catch (e) {
	    this.haveRated = false;
	  }
	  
  },
  methods: {
	  
	  handleRatingClick() {
	      if (!this.isStarted) {
	        // 如果咨询还未开始，显示提示
	        uni.showToast({
	          title: '咨询还未开始，无法评分',
	          icon: 'none',
	          duration: 2000
	        });
	        return;
	      }
	      
	      if (this.haveRated) {
	        // 如果已经评价过，显示提示
	        uni.showToast({
	          title: '您已经评价过了',
	          icon: 'none',
	          duration: 2000
	        });
	        return;
	      }
	      
	      // 符合条件，显示评分界面
	      this.showRating = true;
	    },
	  
		async submitRating() {
		  this.showRating = false;
		  
		  uni.setStorage({
			key: 'have_rated',
			data: true,
			success: () => {
			  this.haveRated = true; // 触发响应式更新
			}
		  });
		  
		  try {
			const res = await uniCloud.callFunction({
			  name: "updateRating",
			  data: {
				uniIdToken: uni.getStorageSync("uni_id_token"),
				consultantId: this.consultantId,
				rating: this.value1
			  }
			});
			
			// 评分成功后显示弹窗
			uni.showModal({
			  title: '评分成功',
			  content: '感谢您的评价！',
			  showCancel: false,
			  success: (res) => {
				if (res.confirm) {
				  console.log('用户点击确定');
				}
			  }
			});
			
			// 如果需要，可以根据云函数返回结果做更多处理
			if (res.result && res.result.code === 0) {
			  console.log('评分更新成功');
			}
		  } catch (error) {
			console.error('评分提交失败:', error);
			uni.showToast({
			  title: '评分提交失败',
			  icon: 'none'
			});
		  }
		},
	  
	  getHide() {
	  	this.showRating = false
	  },
	  
	   onPullDownRefresh() {
	      this.getAppointment().finally(() => {
	        uni.stopPullDownRefresh(); // 停止刷新动画
	      });
	    },
    async getAppointment() {
      const res = await uniCloud.callFunction({
        name: 'getAppointments', 
        data: {
          uniIdToken: uni.getStorageSync('uni_id_token')
        },
      });
      if (res.result && res.result.success) {
        this.appointment.day = res.result.data.day;
        this.appointment.appointedSlot=res.result.data.appointedSlots;
        this.consultantToken = res.result.token;
		console.log(this.consultantToken)
        this.getConsultantInfo();
      } else {
		  // 清空旧数据
		      this.appointment = {
		        day: '',
		        appointedSlot: ''
		      };
		      this.consultantToken = '';
		      this.consultantName = '';
		      this.consultantAvatar = '';
		      this.consultantId = '';
        uni.showToast({ title: '您当前没有任何预约', icon: 'none' });

      }
    },
    async getConsultantInfo() {
      const res = await uniCloud.callFunction({
        name: 'getConsultantInfo',
        data: {
          uniIdToken: this.consultantToken
        }
      });
      if (res.result) {
        this.consultantName = res.result.data.name;
        this.consultantAvatar = res.result.data.avatar;
		this.consultantId = res.result.data.uid;
      }
    },
    async handleCancel() {
	      // 1. 查询用户取消次数
	      const checkRes = await uniCloud.callFunction({
	        name: "manageCancelCount",
			data:{
				action:'get'
			}
	      });
		  console.log(checkRes)
	      if (checkRes.result.data.remainingCancelCount <= 0) {
	        uni.showToast({
	          title: `取消次数不足`,
	          icon: 'none'
	        });
	        return;
	      }
		
      uni.showModal({
        title: '提示',
        content: '确定要取消预约吗？',
        success: async (res) => {
          if (res.confirm) {
            try {
              const res = await uniCloud.callFunction({
                name: "cancelAppointment",
                data: {
                  uniIdToken: uni.getStorageSync('uni_id_token'),
                  day: this.appointment.day,
                  appointedSlot: this.appointment.appointedSlot
                }
              });
            console.log(res)
              // 检查是否成功
              if (res.result && res.success) {
				this.appointment.appointedSlot = '';
				this.appointment.day = '';
                uni.showToast({
                  title: '预约已取消',
                  icon: 'success'
                });
				await uniCloud.callFunction({
				  name: "manageCancelCount",
				  data:{
					  action:"decrease",
					  value:1
				  }
				});
              } else {
                uni.showToast({
                  title: '取消失败，请稍后重试',
                  icon: 'none'
                });
              }
            } catch (error) {
              console.error('取消预约失败', error);
              uni.showToast({
                title: '取消预约失败，请稍后重试',
                icon: 'none'
              });
            }
          }
        }
      });
    },

	goToChat(consultantToken) {
	  if (!this.isTimeReached) {
		uni.showToast({
		  title: '还未到预约时间',
		  icon: 'none'
		});
		return;
	  }
	  
	  const agreed = uni.getStorageSync('privacy_agreed');
	  if(!agreed){
		  	  this.showPrivacyModal = true;
	  }
	  else{
		  this.confirmPrivacy();
	  }
	},
	//开发使用的接口
	goToChatNoLimit(consultantToken) {
	  this.pendingConsultantToken = consultantToken;
	  const agreed = uni.getStorageSync('privacy_agreed');
	  if(!agreed){
	  		this.showPrivacyModal = true;
	  }
	  else{
		  this.confirmPrivacy();
	  }
	},
	
	confirmPrivacy() {
	  //本地存储已经同意过协议
	  uni.setStorageSync('privacy_agreed', true);
	  
	  this.showPrivacyModal = false;
	
	  const consultantToken = this.pendingConsultantToken;
	  this.pendingConsultantToken = null;
	
	  if (!this.appointment?.appointedSlot) return;
	
	  const firstSlot = this.appointment.appointedSlot;
	  const [startTime] = firstSlot.split('-');
	  const [hour, minute] = startTime.split(':').map(Number);
	
	  const date = new Date(this.appointment.day);
	  date.setHours(hour, minute, 0, 0);
	  const timestamp = date.getTime();
	
	  uni.navigateTo({
	    url: `/chatPages/chat/chat?consultantToken=${this.consultantToken}&startTime=${timestamp}`
	  });
	},
	cancelPrivacy() {
	  this.showPrivacyModal = false;
	  this.pendingConsultantToken = null;
	},
	goToPrivacyPage() {
	  // 跳转到隐私协议详情页
	  uni.navigateTo({
		url: '/pages/appointment/privacyNotice'
	  });
	}


  }
};
</script>

<style lang="scss">
/* 全局变量 */
:root {
  --primary-color: #6c8eef;
  --primary-hover: #5a7de0;
  --secondary-color: #f8f9fa;
  --text-color: #2c3e50;
  --border-color: #dee2e6;
  --shadow-sm: 0 4rpx 8rpx rgba(0,0,0,0.05);
  --shadow-md: 0 8rpx 12rpx rgba(0,0,0,0.1);
  --shadow-lg: 0 16rpx 32rpx rgba(0,0,0,0.1);
  --radius-sm: 16rpx;
  --radius-md: 24rpx;
  --radius-lg: 32rpx;
  --spacing-sm: 16rpx;
  --spacing-md: 32rpx;
  --spacing-lg: 48rpx;
}

.container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  padding: 30rpx;
}

.nav-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  padding: 0 20rpx;

  .nav-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #2c3e50;
    position: relative;
    padding-left: 20rpx;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 8rpx;
      height: 32rpx;
      background: #6c8eef;
      border-radius: 4rpx;
    }
  }
}

.appointment-list {
  padding: 20rpx;
  padding-bottom: 60rpx;
}

.appointment-card {
  background: #ffffff;
  border-radius: var(--radius-md);
  box-shadow: var(--shadow-md);
  overflow: hidden;
  margin-bottom: 30rpx;
  transition: all 0.3s ease;
  
  &:active {
    transform: translateY(2rpx);
    box-shadow: var(--shadow-sm);
  }
}

.card-header {
  padding: 30rpx;
  border-bottom: 2rpx solid var(--border-color);
}

.consultant-info {
  display: flex;
  align-items: center;
  
  .info-content {
    margin-left: 30rpx;
    
    .consultant-name {
      font-size: 32rpx;
      font-weight: 600;
      color: var(--text-color);
      margin-bottom: 16rpx;
      display: block;
    }
    
    .appointment-time {
      display: flex;
      align-items: center;
      color: #666;
      font-size: 28rpx;
      
      .u-icon {
        margin-right: 10rpx;
      }
    }
  }
}

.card-content {
  padding: 30rpx;
}

.time-slots {
  .section-title {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 20rpx;
    position: relative;
    padding-left: 20rpx;
    
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 6rpx;
      height: 24rpx;
      background: #6c8eef;
      border-radius: 3rpx;
    }
  }
  
  .slots-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
    
    .slot-item {
      display: flex;
      align-items: center;
      background: var(--secondary-color);
      padding: 16rpx 24rpx;
      border-radius: var(--radius-sm);
      
      .u-icon {
        margin-right: 10rpx;
      }
      
      text {
        color: var(--text-color);
        font-size: 32rpx;
        font-weight: 500;
      }
    }
  }
}

.card-footer {
  padding: 30rpx;
  border-top: 2rpx solid var(--border-color);
  
  .btn-group {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 30rpx;
  }
  
  .chat-btn, .cancel-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 180rpx;
    height: 72rpx;
    border-radius: 36rpx;
    transition: all 0.3s ease;
    font-size: 28rpx;
    
    .u-icon {
      margin-right: 8rpx;
    }
  }
  
  .chat-btn {
    background: #6c8eef;
    border: none;
    box-shadow: 0 4rpx 12rpx rgba(108, 142, 239, 0.3);
    
    &:active {
      transform: translateY(2rpx);
      background: #5a7de0;
      box-shadow: 0 2rpx 6rpx rgba(108, 142, 239, 0.2);
    }
    
    text {
      color: #ffffff;
      font-weight: 500;
    }
  }
  
  .cancel-btn {
    background: none;
    border: 2rpx solid #ff5a5f;
    
    &:active {
      transform: scale(0.98);
      background: rgba(255, 90, 95, 0.1);
    }
    
    text {
      color: #ff5a5f;
    }
  }
}

.empty-state {
  padding: 120rpx 0;
}

.popupwin {
		width: 630rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		// height: 750rpx;
		background: #FFFFFF;
		opacity: 1;
		position: relative;
		z-index: 1000;
	}
	
	.popTitle {
		font-family: PingFangSC-Medium;
		font-size: 34rpx;
		color: #333333;
		text-align: center;
		font-weight: 500;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-wrap: nowrap;
		flex-direction: row;
		align-content: flex-start;
		padding-top: 40rpx;
	}
	
	.close {
		position: absolute;
		right: 30rpx;
		top: 40rpx;
		z-index: 10;
	}
	
	.submit {
		width: 411rpx;
		height: 90rpx;
		background-image: linear-gradient(179deg, #00aaff 1%, #00aaff 100%);
		border-radius: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		flex-wrap: nowrap;
		flex-direction: row;
		align-content: flex-start;
		font-family: PingFangSC-Medium;
		font-size: 32rpx;
		color: #FFFFFF;
		font-weight: 500;
		margin: 0 auto;
		margin-top: 50rpx;
		margin-bottom: 50rpx;
	}
	
	.score {
		margin-left: 80rpx;
		margin-right: 80rpx;
		margin-top: 50rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		flex-wrap: nowrap;
		flex-direction: row;
		align-content: flex-start;
		
			.title {
				font-family: PingFangSC-Regular;
				font-size: 26rpx;
				color: #000000;
				font-weight: 400;
				margin-right: 20rpx;
			}
	}
	
	
	.rating-btn {
	  margin-top: 10rpx;
	  padding: 10rpx 20rpx;
	  border-radius: 6rpx;
	  font-size: 16px;
	  cursor: pointer;
	  transition: 0.3s;
	}
	
	/* 正常可点击状态 */
	.active-btn {
	  background-color: #007aff;
	  color: white;
	}
	
	/* 禁用状态样式 */
	.disabled-btn {
	  background-color: #ccc;
	  color: #888;
	  cursor: not-allowed;
	}

</style>
